//
//  ViewController.m
//  NSStreamCliect
//
//  Created by MyMac on 15/11/2.
//  Copyright © 2015年 tongfang. All rights reserved.
//

#import "ViewController.h"
#import <Foundation/Foundation.h>
@interface ViewController ()<NSStreamDelegate>
@property(nonatomic,strong)NSMutableData*data;
@end

@implementation ViewController

- (void)viewDidLoad {
    [super viewDidLoad];
    self.data=[NSMutableData data];
    NSString*path=[[NSBundle mainBundle]pathForResource:@"屏幕快照 2015-11-02 上午10.19.52.png" ofType:nil];
    NSInputStream*input=[[NSInputStream alloc]initWithFileAtPath:path];
    input.delegate=self;
    [input scheduleInRunLoop:[NSRunLoop currentRunLoop] forMode:NSDefaultRunLoopMode];
    [input open];
    NSLog(@"%ld   %@",input.streamStatus,input.streamError);

    
    // Do any additional setup after loading the view, typically from a nib.
}
- (void)stream:(NSStream *)aStream handleEvent:(NSStreamEvent)eventCode{
    //NSStreamEventHasBytesAvailable  流中有可读取的数据
    //NSStreamEventHasSpaceAvailable   缓存中有空间可写入数据(NSStreamOutput)
    //NSStreamEventEndEncountered 没有数据可操作,操作结束
    
    
    
//NSInputStream:输入流，也就是读取流，这个对象里面包含了一些信息，我们可以通过这个对象拿到里面的信息
    switch (eventCode) {
        case NSStreamEventHasBytesAvailable:{
        NSInputStream*inputStream=(NSInputStream*)aStream;
            //定义一个缓存字符数组，数组的大小要大于最大读取量
            uint8_t byte[2025];
           //读取流中的数据，设定一次最大读取量为1024kb，读完之后存到数组中，反回实际读取量
        //一个信息总量不可能总是1024的倍数
         NSUInteger count=[inputStream read:byte maxLength:2024];
         NSLog(@"%ld",count);
            if (count) {
                //再把缓存中的数据加到数据data中
                [self.data appendBytes:byte length:count];

            }
        }
            
            break;
        case NSStreamEventEndEncountered:{
            UIImage*image=[UIImage imageWithData:self.data];
            UIImageView*imaegView=[[UIImageView alloc]initWithFrame:CGRectMake(100, 100, 100, 100)];
            [self.view addSubview:imaegView];
            imaegView.image=image;
            
            [aStream removeFromRunLoop:[NSRunLoop currentRunLoop] forMode:NSDefaultRunLoopMode];
        
        }
            break;
        default:
            break;
    }
    
   // NSLog(@"%ld   %@",aStream.streamStatus,aStream.streamError);

}
- (void)didReceiveMemoryWarning {
    [super didReceiveMemoryWarning];
    // Dispose of any resources that can be recreated.
}

@end
